package yang.itcode.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yang.itcode.model.Result;
import yang.itcode.service.FileService;

@RestController
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/image")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        String filename = fileService.uploadImage(file);
        return Result.success(filename);
    }

    @GetMapping("/image")
    public ResponseEntity<Resource> getImage(@RequestParam("path") String imagePath) {
        try {
            // 调用Service层获取图片资源
            Resource resource = fileService.getImage(imagePath);

            // 根据文件名确定Content-Type
            String contentType = fileService.determineContentType(imagePath);

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline")
                    .body(resource);
        } catch (Exception ex) {
            return ResponseEntity.notFound().build();
        }
    }
}
